package com.edu.app.service.impl.linkservices;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.app.bean.core.SysUser;
import com.edu.app.bean.core.SysWxUser;
import com.edu.app.bean.linkbeans.SysUserWxUserBind;
import com.edu.app.exception.WechatBindException;
import com.edu.app.mapper.core.SysWxUserMapper;
import com.edu.app.mapper.linkmappers.SysUserWxUserBindMapper;
import com.edu.app.model.wechat.WxErrorException;
import com.edu.app.service.impl.SysBaseServiceImpl;
import com.edu.app.service.sys.linkservices.SysUserWxUserService;
import com.edu.app.service.sys.wechat.WechatUserService;
import com.edu.app.util.json.JsonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class SysUserWxUserServiceImpl
        extends SysBaseServiceImpl<SysUserWxUserBind,SysUserWxUserBindMapper>
        implements SysUserWxUserService {
    Logger logger = LoggerFactory.getLogger(SysUserWxUserServiceImpl.class);

    @Autowired
    SysUserWxUserBindMapper sysUserWxUserBindMapper;


    @Autowired
    SysWxUserMapper sysWxUserMapper;

    @Autowired
    WechatUserService wechatUserService;

    @Autowired
    BeanWrapperImpl beanWrapper;

    @Override
    public List<SysWxUser> getWxUserByUserId(Integer id){

        List<SysWxUser> sysWxUsers = sysUserWxUserBindMapper.getWxUserListByUserId(id);
        return sysWxUsers;
    }

    @Override
    public  SysUserWxUserBind getUserWxUser(Integer user_id, Integer wxUser_id){
        return sysUserWxUserBindMapper.getUserWxUser(user_id, wxUser_id);
    }

    @Override
    public  SysWxUser getWxUser(String openId){
        QueryWrapper<SysWxUser> queryMapper = new QueryWrapper<SysWxUser>();
        queryMapper.lambda().eq(SysWxUser::getOpenid,openId);
        return sysWxUserMapper.selectOne(queryMapper);
    }

    @Override
    @Transactional
    public  SysUserWxUserBind  createUserWxUserBind (SysUser sysUser, Integer tenant_id, String openId)
             throws WechatBindException {
        Integer user_id = sysUser.getId();
        SysUserWxUserBind sysUserWxUserBind =  sysUserWxUserBindMapper.getUserWxUserBindByOpendId(openId);
        if(sysUserWxUserBind != null){
            if(sysUserWxUserBind.getUser_id() != user_id || sysUserWxUserBind.getTenant_id() != tenant_id ){
                String str = String.format("This wechat user %s has been bound with another account %s.",
                                            sysUserWxUserBind.getWxuser_id(),
                                            sysUserWxUserBind.getUser_id());
                throw new WechatBindException(str);
            }
        }else{
            QueryWrapper<SysWxUser> queryMapper = new QueryWrapper<SysWxUser>();
            queryMapper.lambda().eq(SysWxUser::getOpenid,openId);
            SysWxUser sysWxUser = sysWxUserMapper.selectOne(queryMapper);
            if(sysWxUser != null){
                if(sysWxUser.getTenant_id() != tenant_id){
                    String str = String.format("This wechat user %s belongs to another tenant %s .",
                            sysWxUser.getTenant_id()
                             );
                    throw new WechatBindException(str);
                }
                sysUserWxUserBind = new SysUserWxUserBind();
                sysUserWxUserBind.initializeSystemColumns(sysUser.getUsername());
                sysUserWxUserBind.setUser_id(user_id);
                sysUserWxUserBind.setWxuser_id(sysWxUser.getId());
                sysUserWxUserBind.setTenant_id(tenant_id);
                sysUserWxUserBindMapper.insert(sysUserWxUserBind);
            }
            else{
                //create wxuser
                try{
                    String  userinfo                  = wechatUserService.userInfo(openId);
                    Map<String,Object> userInfoMap    = JsonUtil.fromJson(userinfo,Map.class);
                    SysWxUser wxUser                        = new SysWxUser();

                    wxUser.initializeSystemColumns(sysUser.getUsername());
                    beanWrapper.setBeanInstance(wxUser);
                    beanWrapper.setPropertyValues(userInfoMap);

                    sysWxUserMapper.insert(wxUser);

                    sysUserWxUserBind = new SysUserWxUserBind();
                    sysUserWxUserBind.initializeSystemColumns(sysUser.getUsername());
                    sysUserWxUserBind.setUser_id(user_id);
                    sysUserWxUserBind.setWxuser_id(sysWxUser.getId());
                    sysUserWxUserBind.setTenant_id(tenant_id);
                    sysUserWxUserBindMapper.insert(sysUserWxUserBind);
                }
                catch(WxErrorException wxe){
                    logger.error(wxe.getMessage());
                    throw new WechatBindException(wxe.getMessage());
                }
                catch(IOException ioe){
                    logger.error(ioe.getMessage());
                    throw new WechatBindException(ioe.getMessage());
                }
            }
        }
        return sysUserWxUserBind;
    }
    @Override
    public Integer deleteWxUserByUserId(Integer user_id){
        return sysUserWxUserBindMapper.deleteUserWxUserBindByUserId(user_id);
    }
    @Override
    public
    Integer deleteWxUserByWxUserId(Integer wxUser_id){
        return sysUserWxUserBindMapper.deleteUserWxUserBindByWxUserId(wxUser_id);
    }
}
